package com.example.demo.service;

import com.example.demo.Board;
import com.example.demo.dao.BoardMapper;
import com.example.demo.util.MyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BoardService {
    private static final Logger log = LoggerFactory.getLogger(BoardService.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SudokuSolution solution;

    @Autowired
    private BoardMapper mapper;

    public String getNewBoard() {
        String key = stringRedisTemplate.randomKey();
        if (key == null) {
            for (int i = 1; i <= 10; i++) {
                String board = mapper.getBoardById(i);
                stringRedisTemplate.opsForValue().set(board, "0");
            }
            return getNewBoard();
        }
        String value = stringRedisTemplate.opsForValue().get(key);
        assert value != null;
        if (Integer.parseInt(value) > 5) {
            stringRedisTemplate.delete(key);
            Board board = mapper.createBoard();
            int id = board.getId();
            log.info("选中了第" + id + "道题目");
            return board.getContent();
        } else {
            stringRedisTemplate.opsForValue().set(key, value + 1);
            return key;
        }
    }

    public String[] getAnswer(String problem) {
        if (problem == null || problem.length() != 81) {
            return new String[0];
        }
        String[] split = MyUtils.split(problem);
        char[][] chars = MyUtils.toCharArray(split);
        solution.solveSudoku(chars);
        return MyUtils.toString(chars);
    }
}
